package com.cg.interceptor;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.cg.common.BaseContext;
import com.cg.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * 登录拦截器
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 跳过OPTIONS预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        
        String authHeader = request.getHeader("Authorization");
        
        // 如果没有Authorization头，返回401
        if (authHeader == null || authHeader.trim().isEmpty()) {
            response.sendError(401, "未登录，请先登录");
            return false;
        }
        
        // 提取Bearer token
        String token = null;
        if (authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
        } else {
            token = authHeader; // 兼容直接传递token的情况
        }
        
        // 如果token为空，返回401
        if (token == null || token.trim().isEmpty()) {
            response.sendError(401, "未登录，请先登录");
            return false;
        }
        
        try {
            // JWT校验
            Map<String, Object> claims = JwtUtil.parseToken(token);
            Long userId = Long.valueOf(claims.get("userId").toString());
            
            // 设置用户上下文
            BaseContext.setCurrentId(userId);
            log.info("用户 {} 通过身份验证", userId);
            return true;
            
        } catch (TokenExpiredException e) {
            response.sendError(401, "登录过期，重新登录");
            return false;
        } catch (Exception e) {
            log.error("JWT解析失败: {}", e.getMessage());
            response.sendError(401, "未登录，请先登录");
            return false;
        }
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 清理用户上下文
        BaseContext.removeCurrentId();
    }
}

